﻿using System;
using System.IO;
using System.Windows.Forms;

using DreamCube.Foundation.Basic.Utility;
using Top.Api.Request;
using Top.Api.Response;

namespace DreamCube.TaobaoGJ.BLL
{
    public static class SessionKey
    {
        /// <summary>
        /// 当前访问的店铺ID号
        /// </summary>
        public static String SessionNick
        {
            get;
            set;
        }

        /// <summary>
        /// 确认SessionKey是有效的
        /// </summary>
        public static Boolean ConfirmSessionKey()
        {
            try
            {
                UserSellerGetRequest userReq = new UserSellerGetRequest
                {
                    Fields = "user_id"
                };
                UserSellerGetResponse userResp = new UserSellerGetResponse();
                String sessionKey = GetSessionKey();
                if (String.IsNullOrEmpty(sessionKey))
                    return false;
                if (TB_AppKeyFunc.GetTopClient().Execute<UserSellerGetResponse>(userReq, sessionKey).IsError)
                    return false;
                return true;
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            return false;
        }

        /// <summary>
        /// 获取授权编码
        /// </summary>
        /// <returns></returns>
        public static String GetSessionKey()
        {
            String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Properties.Resources.SessionKeyFileName);
            String textValue = MyIO.ReadText(filePath);
            String[] values = textValue.Split('=');
            SessionNick = values[0];
            return values[1];
        }

        /// <summary>
        /// 保存Sessionkey值
        /// </summary>
        /// <param name="sessionKey"></param>
        public static void SaveSessionKey(String sessionKey, String nick)
        {
            String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Properties.Resources.SessionKeyFileName);
            MyIO.Write(filePath, nick + "=" + sessionKey, false);
        }
    }
}
